package cn.oscar;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
//@Order(-1)//过滤器执行的优先级 越小的越先执行
/*
* 自定义过滤器，配置业务逻辑
*
* */
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        //获取参数的authorization 参数
        String auth = params.getFirst("authorization");

        //判断数值是否等于 admin
        if (!"admin".equals(auth)){
            //是 放行
            return chain.filter(exchange);
        }

        //否 拦截
        //同时设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    /**
     * 实现ordered接口 ，重写方法，设置过滤器执行的优先级 越小的越先执行
     * @return 返回执行顺序
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
